package com.anolesoft.yr.mbus.cont.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anolesoft.yr.mbus.cont.dao.*;
import com.anolesoft.yr.mbus.cont.entity.*;
import com.anolesoft.yr.mbus.cont.service.ContWordCreatService;
import com.anolesoft.yr.mbus.contm.dao.ContmMainDao;
import com.anolesoft.yr.mbus.contm.dao.ContmStyleItemDao;
import com.anolesoft.yr.mbus.contm.dao.ContmStyleMainDao;
import com.anolesoft.yr.mbus.contm.entity.*;
import com.anolesoft.yr.mbus.contm.entity.Paragraph;
import com.anolesoft.yr.mbus.contm.util.*;
/*import com.anolesoft.yr.mbus.prod.base.entity.ProdBaseService;
import com.anolesoft.yr.mbus.prod.base.entity.ProdBaseServiceValue;
import com.anolesoft.yr.mbus.prod.base.mapper.ProdBaseServiceMapper;
import com.anolesoft.yr.mbus.prod.base.mapper.ProdBaseServiceValueMapper;*/
import com.anolesoft.yr.mbus.prod.base.mapper.ProdBaseServiceMapper;
import com.anolesoft.yr.mbus.prod.base.mapper.ProdBaseServiceValueMapper;
import com.anolesoft.yr.mbus.prod.base.vo.ProdBaseServiceQueryVO;
import com.anolesoft.yr.mbus.prod.model.entity.ProdProduction;
import com.anolesoft.yr.mbus.prod.model.mapper.ProdProductionMapper;
import com.anolesoft.yr.mbus.prod.model.mapper.ProdServiceMapper;
import com.anolesoft.yr.mbus.prod.model.mapper.ProdTypeMapper;
import com.anolesoft.yr.mbus.prod.model.vo.ProdServiceQueryVO;
import com.anolesoft.yr.mbus.prod.model.vo.ProdTypeQueryVO;
import com.baomidou.mybatisplus.generator.config.IFileCreate;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.dom4j.*;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Administrator
 */
@AllArgsConstructor
@Service
@Slf4j
public class ContWordCreatServiceImpl implements ContWordCreatService {


    private ContVariableDao contVariableDao;
    private ContMainDao contMainDao;
    private ContListDao contListDao;
    private ContListServiceDao contListServiceDao;
    private ContContentDao contContentDao;
    private ContmMainDao contmMainDao;
    private ContmStyleItemDao contmStyleItemDao;
    private ContmStyleMainDao contmStyleMainDao;
    private ContPaymentDao contPaymentDao;
    private ProdBaseServiceMapper prodBaseServiceMapper;
    private ProdBaseServiceValueMapper prodBaseServiceValueMapper;
    private ProdProductionMapper prodProductionMapper;
    private ProdServiceMapper prodServiceMapper;
    private ProdTypeMapper prodTypeMapper;
    /**
     * 获取变量值
     */
    @Override
    public Map<String, String> getContValue(ContMain contMain,List<ContVariable> contVariables) {
        //获取所有变量
        //获取合同表内的所有内容
        //将合同表的字段名与字段值形成一个map
        Map<String, String> map = contMain.toMap();
        //过滤出来都有哪些值是从m合同表中获取的
        List<ContVariable> contList = contVariables.stream().filter(a ->("java").equals(a.getVarType())).collect(Collectors.toList());
        //建立结果map
        Map<String, String> resultMap = new HashMap<>();
        //确定map中都有哪些key 省的再取值的时候报错
        List<String> collect = map.keySet().stream().collect(Collectors.toList());
        //首先将合同表里的数据存进来
        contList.forEach(a->{
            if (collect.contains(a.getVarVal())){
                resultMap.put(a.getVarName(),map.get(a.getVarVal())==null?"":map.get(a.getVarVal()));
            }
        });
        List<ContVariable> contValueList = contVariables.stream().filter(a ->("value").equals(a.getVarType())).collect(Collectors.toList());
        Map<String, String> collect1 = contValueList.stream().collect(Collectors.toMap(ContVariable::getVarName, ContVariable::getVarVal));
        resultMap.putAll(collect1);
        return resultMap;
    }

    public void exeucte(List<ContContent> children, List<ContContent> save) {
        for (ContContent contContent : children) {
            save.add(contContent);
            List<ContContent> contContentsContent = contContent.getContContentsContent();
            save.addAll(contContentsContent.stream().sorted(Comparator.comparing(ContContent::getOrder)).collect(Collectors.toList()));
            List<ContContent> contContentsTitle = contContent.getContContentsTitle();
            if (!contContentsTitle.isEmpty()) {
                exeucte(contContentsTitle, save);
            }
        }
    }

    @Override
    public String executeContent(String contMainUid) throws Exception {
        List<Paragraph> paragraphList = Lists.newArrayList();
        //查询出所有的内容
        ContContentExample contContentExample = new ContContentExample();
        contContentExample.createCriteria().andContMainUidEqualTo(contMainUid);
         List<ContContent> contContents = contContentDao.selectByExample(contContentExample);
        //递归排序的前提内容 找到所有的标题起点
        List<ContContent> start = contContents.stream().filter(a -> a.getParentUid() == null || "".equals(a.getParentUid())).sorted(Comparator.comparingInt(ContContent::getOrderCode)).collect(Collectors.toList());
        //递归排序，将所有的内容的order填写上对应的数字，将树形数据展开
        contContentSort(start,contContents,new AtomicInteger());
        //重新按照order排序
        contContents = contContents.stream().sorted(Comparator.comparingDouble(ContContent::getOrder)).collect(Collectors.toList());

        //下面获取的是样式信息 获取样式xml 用来替换
        ContMain contMain = contMainDao.selectById(contMainUid);
        String styleMainUid = contmMainDao.selectById(contMain.getContTemplateUid()).getStyleMainUid();
        ContmStyleItemExample contmStyleItemExample = new ContmStyleItemExample();
        contmStyleItemExample.createCriteria().andContmStyleUidEqualTo(styleMainUid);
        List<ContmStyleItem> contmStyleItems = contmStyleItemDao.selectByExample(contmStyleItemExample);
        //将每个页的内容单独的分组拿出来
        List<ContContent> sy = contContents.stream().filter(a -> PageType.FIRST_PAGE.equals(a.getPageType())).collect(Collectors.toList());
        List<ContContent> fy = contContents.stream().filter(a -> PageType.SECOND_PAGE.equals(a.getPageType())).collect(Collectors.toList());
        List<ContContent> nry = contContents.stream().filter(a -> PageType.CONTENT_PAGE.equals(a.getPageType())).collect(Collectors.toList());
        List<ContContent> qzy = contContents.stream().filter(a -> PageType.SIGN_PAGE.equals(a.getPageType())).collect(Collectors.toList());
        List<ContContent> dly = contContents.stream().filter(a -> PageType.MAKE_PAGE.equals(a.getPageType())).collect(Collectors.toList());
        List<ContContent> fjy = contContents.stream().filter(a -> PageType.LAST_PAGE.equals(a.getPageType())).collect(Collectors.toList());
        ContmStyleItem contentNumItem = contmStyleItems.stream().filter(a->ItemType.CONTENT_PAGE_LIST_NUM.equals(a.getItemType())).collect(Collectors.toList()).get(0);
        ContmStyleItem contentAbNumItem = contmStyleItems.stream().filter(a->ItemType.CONTENT_PAGE_LIST_ABSTRACT_NUM.equals(a.getItemType())).collect(Collectors.toList()).get(0);
        ContmStyleItem lastNumItem = contmStyleItems.stream().filter(a->ItemType.LAST_PAGE_LIST_NUM.equals(a.getItemType())).collect(Collectors.toList()).get(0);
        ContmStyleItem lastAbNumItem = contmStyleItems.stream().filter(a->ItemType.LAST_PAGE_LIST_ABSTRACT_NUM.equals(a.getItemType())).collect(Collectors.toList()).get(0);
        ContmStyleItem numberPage = contmStyleItems.stream().filter(a->ItemType.NUMBER_PAGE.equals(a.getItemType())).collect(Collectors.toList()).get(0);

        boolean contentNumFlag = false;
        boolean lastNumFlag = false;
        //这个是整个文档总体的页面属性，当p中没有sectpr时 默认使用这个。
        ContmStyleItem sectPr = contmStyleItems.stream().filter(a -> PageType.SYSTEM_PAGE.equals(a.getPageType())).collect(Collectors.toList()).get(0);
        ContmStyleItem tbl = contmStyleItems.stream().filter(a -> PageType.TABLE.equals(a.getPageType())).collect(Collectors.toList()).get(0);
        Element tblElement = DocumentHelper.parseText(tbl.getCode()).getRootElement();
        List<ContVariable> contVariables = contVariableDao.selectByExample(new ContVariableExample());
        int contentNumList = 10000;
        int lastNumList = 10000;
        //下面几个循环为了 处理标题的级别 并与样式信息进行匹配。
         for (int i = 0; i < sy.size(); i++) {
            ContContent a = sy.get(i);
            List<Paragraph> paragraphs = xmlExecute(a,0,contMain,contVariables);
            paragraphList.addAll(paragraphs);
        }
        for (int i = 0; i < fy.size(); i++) {
            ContContent a = fy.get(i);
            List<Paragraph> paragraphs = xmlExecute(a,0,contMain,contVariables);
            paragraphList.addAll(paragraphs);
        }
        for (int i = 0; i < dly.size(); i++) {
            ContContent a = dly.get(i);
            List<Paragraph> paragraphs = xmlExecute(a,0,contMain,contVariables);
            paragraphList.addAll(paragraphs);
        }
        for (int i = 0; i < nry.size(); i++) {
            ContContent a = nry.get(i);
            AtomicInteger lvl = new AtomicInteger();
            lvl.set(1);
            Lvl(lvl,a,nry);
            if (ItemType.CONTENT.equals(a.getItemType())){
                lvl.addAndGet(-1);
                if (lvl.get()<0){
                    lvl.set(0);
                }
            }
            List<Paragraph> paragraphs = xmlExecute(a,lvl.get(),contMain,contVariables);

            paragraphList.addAll(paragraphs);
        }
        for (int i = 0; i < qzy.size(); i++) {
            ContContent a = qzy.get(i);
            List<Paragraph> paragraphs = xmlExecute(a,0,contMain,contVariables);
            paragraphList.addAll(paragraphs);
        }

        for (int i = 0; i < fjy.size(); i++) {
            ContContent a = fjy.get(i);
            AtomicInteger lvl = new AtomicInteger();
            lvl.set(0);
            Lvl(lvl,a,fjy);
            if (ItemType.CONTENT.equals(a.getItemType())){
                lvl.addAndGet(-1);
                if (lvl.get()<0){
                    lvl.set(0);
                }
            }
            List<Paragraph> paragraphs = xmlExecute(a,lvl.get()>0?lvl.get():0,contMain,contVariables);
            paragraphList.addAll(paragraphs);
        }
        //匹配xml
        for (int i = 0; i < paragraphList.size(); i++) {
            String type = paragraphList.get(i).getType();
            Integer lvl = paragraphList.get(i).getLvl();
            if(lvl==null){
                lvl = 0;
            }
            if (ItemType.NEXT_LINE.equals(type)){
                Element element = DocumentHelper.createElement("w:p");
                Element ppr = DocumentHelper.createElement("w:pPr");
                Element jc = DocumentHelper.createElement("w:jc");
                Element rpr = DocumentHelper.createElement("w:rPr");
                jc.addAttribute("val","right");
                ppr.add(jc);
                ppr.add(rpr);
                element.add(ppr);
                paragraphList.get(i).setXml(element.asXML());
            }else if(ItemType.TABLE.equals(type)){
                continue;
            }else{
                for (int j = 0; j <contmStyleItems.size() ; j++) {
                    ContmStyleItem contmStyleItem = contmStyleItems.get(j);
                    if (contmStyleItem.getLvl().intValue() == lvl.intValue()&&contmStyleItem.getItemType().equals(type)){
                        paragraphList.get(i).setXml(contmStyleItem.getCode());
                    }else if (ItemType.CONTENT_PAGE_LIST.equals(type)&&contmStyleItem.getItemType().equals(type)){
                        paragraphList.get(i).setXml(contmStyleItem.getCode());

                    }
                }
            }


        }
        //准备生成document.xml
        //1。首先拿出xml头。
        Element rootElement = DocumentHelper.parseText(Docx.TITLE).getRootElement();
        //向xml文件中增加P节点
        for (int i = 0; i < paragraphList.size(); i++) {
            //此IF处理空行
            if (ItemType.NEXT_LINE.equals(paragraphList.get(i).getType())){
                contentNumFlag = false;
                lastNumFlag = false;
                Element styleElement = DocumentHelper.createElement("w:p");
                Element ppr = DocumentHelper.createElement("w:pPr");
                Element ind = DocumentHelper.createElement("w:ind");
                Element rpr = DocumentHelper.createElement("w:rPr");
                Element rFonts = DocumentHelper.createElement("w:rFonts");
                rFonts.addAttribute("w:hint","eastAsia");
                ind.addAttribute("w:left","425");
                rpr.add(rFonts);
                ppr.add(ind);
                ppr.add(rpr);
                styleElement.add(ppr);
                rootElement.add(styleElement);
            }else if (ItemType.TABLE.equals(paragraphList.get(i).getType())){
                contentNumFlag = false;
                lastNumFlag = false;

                Paragraph paragraph = paragraphList.get(i);
                if (TableType.PAYMENT_TABLE.equals(paragraph.getXml())){
                    ContPaymentExample contPaymentExample = new ContPaymentExample();
                    contPaymentExample.setOrderByClause("order_code");
                    contPaymentExample.createCriteria().andContMainUidEqualTo(contMainUid);
                    List<ContPayment> contPayments = contPaymentDao.selectByExample(contPaymentExample);
                    List<List<String>> lists = Lists.newArrayList();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    contPayments.forEach(a->{
                        List<String> values = Lists.newArrayList();
                        values.add(simpleDateFormat.format(a.getPlanPaymentTime()));
                        values.add(a.getPlanAmount().toString());
                        values.add(a.getRemark());
                        lists.add(values);
                    });

                    Element element = DocUtil.formatDocTable(tblElement,  toColumn(TableType.PAYMENT_HEADER), lists);
                    rootElement.add(element);
                }else if(TableType.PRODUCT_TABLE.equals(paragraph.getXml())){
                    ContListServiceExample contListServiceExample = new ContListServiceExample();
                    contListServiceExample.createCriteria().andContMainUidEqualTo(contMainUid);
                    List<ContListService> contListServices = contListServiceDao.selectByExample(contListServiceExample);
                    ContListExample contListExample = new ContListExample();
                    contListExample.createCriteria().andContMainUidEqualTo(contMainUid);
                    List<ContList> contLists = contListDao.selectByExample(contListExample);
                    Map<String, String> TypeNameMap = prodTypeMapper.queryProdTypeName().stream().collect(Collectors.toMap(ProdTypeQueryVO::getObjuid, ProdTypeQueryVO::getTypeName));
                    List<String> productUids = contLists.stream().map(ContList::getProdProductUid).distinct().collect(Collectors.toList());
                    for (int j = 0; j < productUids.size(); j++) {
                        List<List<String>> trValues = Lists.newArrayList();
                        String product = productUids.get(j);
                        ProdProduction prodProductionTemp = prodProductionMapper.queryProdProductionByUid2(product);
                            //当前分支
                        List<ContList> branch = contLists.stream().filter(a -> product.equals(a.getProdProductUid())).collect(Collectors.toList());
                        ProdProduction prodProduction = prodProductionMapper.queryProdProductionByUid2(product);
                        List<ProdServiceQueryVO> prodServiceQueryVOS = prodServiceMapper.queryProdServiceNameByUid(prodProduction.getObjuid());
                        List<String> headers = Lists.newArrayList();
                        if(TypeNameMap.get(prodProductionTemp.getProdTypeUid()).contains("备件")){
                            headers.addAll(TableType.SPARE_HEADER);
                        }else{
                            headers.addAll(TableType.SELL_HEADER);

                        }
                        headers.addAll(prodServiceQueryVOS.stream().map(ProdServiceQueryVO::getText).collect(Collectors.toList()));
                        JSONArray headArray = toColumn(headers);
                        for (int k = 0; k < branch.size(); k++) {
                            ContList contList = branch.get(k);
                            Map<String,String> contListServiceMap = contListServices.stream().filter(a -> a.getContListUid().equals(contList.getObjuid())).collect(Collectors.toMap(ContListService::getServiceOption,ContListService::getServiceOptionValue));
                            List<String> values = Lists.newArrayList();
                            for (int l = 0; l <headers.size() ; l++) {
                                String header = headers.get(l);
                                if(TableType.HEADER_ORDER.equals(header)){
                                    values.add(l+"");
                                }else if (TableType.HEADER_MODEL.equals(header)){
                                    values.add("型号名称");
                                }else if (TableType.HEADER_PRICE.equals(header)){
                                    values.add(contList.getPrice()+"");
                                }else if (TableType.HEADER_QUANTITY.equals(header)){
                                    values.add(contList.getQuantity()+"");
                                }else if (TableType.HEADER_SN.equals(header)){
                                    values.add(contList.getSnCode());
                                }else {
                                    if (contListServiceMap.keySet().contains(header)){
                                        values.add(contListServiceMap.get(header));
                                    }else{
                                        values.add("");
                                    }
                                }
                            }
                            trValues.add(values);
                        }
                       rootElement.add(DocUtil.formatDocTable(tblElement,headArray,trValues));

                    }

                }
            }else if(ItemType.CONTENT_PAGE_LIST.equals(paragraphList.get(i).getType())){
                lastNumFlag = false;
                if(paragraphList.get(i).getXml()!=null){
                    if (!contentNumFlag){
                        contentNumList++;
                    }
                    Element styleElement = DocumentHelper.parseText(paragraphList.get(i).getXml()).getRootElement();
                    Attribute numAttribute = styleElement.element("pPr").element("numPr").element("numId").attribute("val");
                    numAttribute.setValue(Integer.toString(contentNumList));

                    Element pElement = DocUtil.getPElement(paragraphList.get(i).getRows(), styleElement);
                    rootElement.add(pElement);
                    contentNumFlag = true;

                }
            }else if(ItemType.LAST_PAGE_CONTENT_LIST.equals(paragraphList.get(i).getType())){
                contentNumFlag = false;
                if(paragraphList.get(i).getXml()!=null){
                    if (!lastNumFlag){
                        lastNumList++;
                    }
                    Element styleElement = DocumentHelper.parseText(paragraphList.get(i).getXml()).getRootElement();
                    Attribute numAttribute = styleElement.element("pPr").element("numPr").element("numId").attribute("val");
                    numAttribute.setValue(Integer.toString(contentNumList));
                    Element pElement = DocUtil.getPElement(paragraphList.get(i).getRows(), styleElement);
                    rootElement.add(pElement);
                    lastNumFlag = true;

                }
            }else{
                contentNumFlag = false;
                lastNumFlag = false;

                if(paragraphList.get(i).getXml()!=null){
                    Element styleElement = DocumentHelper.parseText(paragraphList.get(i).getXml()).getRootElement();
                    Element pElement = DocUtil.getPElement(paragraphList.get(i).getRows(), styleElement);
                    rootElement.add(pElement);
                }

            }
        }
        Element lastNumElement = DocumentHelper.parseText(lastNumItem.getCode()).getRootElement();
        Element lastAbNumElement = DocumentHelper.parseText(lastAbNumItem.getCode()).getRootElement();
        Element contentNumElement = DocumentHelper.parseText(contentNumItem.getCode()).getRootElement();
        Element contentAbNumElement = DocumentHelper.parseText(contentAbNumItem.getCode()).getRootElement();
        Element numPageElement = DocumentHelper.parseText(numberPage.getCode()).getRootElement();

        while (lastNumList>20000){
            Element copy = lastAbNumElement.createCopy();
            Attribute attribute = copy.attribute("abstractNumId");
            attribute.setValue(Integer.toString(lastNumList));

            Element numCopy = lastNumElement.createCopy();
            Attribute numAttribute_ = numCopy.attribute("numId");
            numAttribute_.setValue(Integer.toString(lastNumList));
            Attribute numAttribute = numCopy.element("abstractNumId").attribute("val");
            numAttribute.setValue(Integer.toString(lastNumList));
            numPageElement.add(copy);
            numPageElement.add(numCopy);
            lastNumList--;
        }
        while (contentNumList>10000){
            Element copy = contentAbNumElement.createCopy();
            Attribute attribute = copy.attribute("abstractNumId");
            attribute.setValue(Integer.toString(contentNumList));
            Element numCopy = contentNumElement.createCopy();
            Attribute numAttribute_ = numCopy.attribute("numId");
            numAttribute_.setValue(Integer.toString(contentNumList));
            Attribute numAttribute = numCopy.element("abstractNumId").attribute("val");
            numAttribute.setValue(Integer.toString(contentNumList));
            numPageElement.add(copy);
            numPageElement.add(numCopy);
            contentNumList--;
        }
        //最后在文件中加入文件属性。
        rootElement.add(DocumentHelper.parseText(sectPr.getCode()).getRootElement());
        ContmStyleMain contmStyleMain = contmStyleMainDao.selectByPrimaryKey(styleMainUid);
        String path= contmStyleMain.getStylePath();
      //  FileUtil.deleteAllFilesOfDir(new File(path + "word/document.xml"));
        FileUtil.deleteAllFilesOfDir(new File(path + "word/numbering.xml"));

        String content = rootElement.asXML();
        String numberContent = numPageElement.asXML();
        File documentFile = new File(path);

        String path2 = documentFile.getParent() + File.separator + documentFile.getName().substring(0, documentFile.getName().indexOf(".")) + File.separator;
        File file = docxToZip(documentFile);
        String encoding = "utf-8";
        String docxName = file.getParent()+File.separator+file.getName().substring(0,file.getName().indexOf("."))+contMainUid+".docx";
        FileUtil.write(path2 + "word/document.xml", content, encoding);
      //  FileUtil.write(path2 + "word/numbering.xml", numberContent, encoding);

        AntZipUtil.zip(file.getParent()+File.separator+file.getName().substring(0,file.getName().indexOf("."))+File.separator,docxName,"temp" );
        return docxName;
    }
    public JSONArray toColumn(List<String> columns){
        JSONArray jsonArray = new JSONArray();
        columns.forEach(a->{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("column",a);
            jsonArray.add(jsonObject);
        });
        return jsonArray;
    }
    public File docxToZip(File file) throws IOException {
        File a = new File(file.getParent() + File.separator + file.getName().substring(0, file.getName().indexOf(".")) + ".zip");
        file.renameTo(a);
        File newFile = new File(a.getParent() + File.separator + a.getName());
        ZipUtil.unZipFiles(newFile.getParent() + File.separator + newFile.getName(), newFile.getParent() + File.separator + newFile.getName().substring(0, newFile.getName().indexOf(".")));
        return newFile;
    }

    private void Lvl(AtomicInteger lvl ,ContContent contContent,List<ContContent> contContents){
        if (contContent.getParentUid() == null||"".equals(contContent.getParentUid())){
            log.info(contContent.getContent()+"等级是"+lvl);
        }else {
            for (int i = 0; i < contContents.size(); i++) {
                if (contContent.getParentUid().equals(contContents.get(i).getObjuid())){
                    lvl.addAndGet(1);
                    Lvl(lvl,contContents.get(i),contContents);
                }
            }

        }
    }


    private String getItemType(String page,String type,String alisa,boolean isList){
        if (PageType.FIRST_PAGE.equals(page)&&ItemType.TITLE.equals(type)&&!isList){
            return ItemType.FIRST_PAGE_TITLE;
        }else if(PageType.FIRST_PAGE.equals(page)&&ItemType.CONTENT.equals(type)&&!isList){
            return ItemType.FIRST_PAGE_CONTENT;
        }else if(PageType.FIRST_PAGE.equals(page)&&ItemType.CONTENT.equals(type)&&isList){
            return ItemType.SECOND_PAGE_LIST;


        }else if(PageType.SECOND_PAGE.equals(page)&&ItemType.CONTENT.equals(type)&&!isList){
            return ItemType.SECOND_PAGE_CONTENT;
        }else if(PageType.SECOND_PAGE.equals(page)&&ItemType.CONTENT.equals(type)&&isList){
            return ItemType.SECOND_PAGE_LIST;
        }else if(PageType.SECOND_PAGE.equals(page)&&ItemType.TITLE.equals(type)&&!isList){
            return ItemType.SECOND_PAGE_TITLE;
        //订立页
        }else if(PageType.MAKE_PAGE.equals(page)&&ItemType.TITLE.equals(type)&&ItemType.ALISA_MAKE_PAGE_FIRST_TITLE.equals(alisa)){
            return ItemType.MAKE_PAGE_TITLE;
        }else if(PageType.MAKE_PAGE.equals(page)&&ItemType.TITLE.equals(type)&&ItemType.ALISA_MAKE_PAGE_SECOND_TITLE.equals(alisa)){
            return ItemType.MAKE_PAGE_SECOND_TITLE;
        }else if(PageType.MAKE_PAGE.equals(page)&&ItemType.CONTENT.equals(type)&&!isList){
            return ItemType.MAKE_PAGE_CONTENT;


        }else if(PageType.CONTENT_PAGE.equals(page)&&ItemType.TITLE.equals(type)){
            return ItemType.CONTENT_PAGE_TITLE;
        }else if(PageType.CONTENT_PAGE.equals(page)&&ItemType.CONTENT.equals(type)&&!isList){
            return ItemType.CONTENT_PAGE_CONTENT;
        }else if(PageType.CONTENT_PAGE.equals(page)&&ItemType.CONTENT.equals(type)&&isList){
            return ItemType.CONTENT_PAGE_LIST;


        }else if(PageType.SIGN_PAGE.equals(page)&&ItemType.TITLE.equals(type)){
            return ItemType.SIGN_PAGE_TITLE;
        }else if(PageType.SIGN_PAGE.equals(page)&&ItemType.CONTENT.equals(type)){
            return ItemType.SIGN_PAGE_CONTENT;



        }else if(PageType.LAST_PAGE.equals(page)&&ItemType.TITLE.equals(type)&&ItemType.ALISA_LAST_PAGE_GENERAL_TITLE.equals(alisa)){
            return ItemType.LAST_PAGE_TITLE;
        }else if(PageType.LAST_PAGE.equals(page)&&ItemType.CONTENT.equals(type)&&!isList){
            return ItemType.LAST_PAGE_CONTENT;
        }else if (PageType.LAST_PAGE.equals(page)&&ItemType.TITLE.equals(type)){
            return ItemType.LAST_PAGE_TITLE_LIST;
        }else if (PageType.LAST_PAGE.equals(page)&&ItemType.CONTENT.equals(type)&&isList){
            return ItemType.LAST_PAGE_CONTENT_LIST;
        }

        return ItemType.CONTENT_PAGE_CONTENT;
    }
    public List<Paragraph> xmlExecute(ContContent contContent,Integer lvl,ContMain contMain,List<ContVariable>contVariables) throws DocumentException {
/*        ContVariableExample contVariableExample = new ContVariableExample();
        contVariableExample.createCriteria().andVarTypeEqualTo("table");
        List<ContVariable> contVariables = contVariableDao.selectByExample(contVariableExample);*/
        if(contContent.getContent()==null){
            contContent.setContent("");
        }
        String content = "<p>"+contContent.getContent().replaceAll("&nbsp;"," ")+"</p>";
        List<Paragraph> paragraphs = Lists.newArrayList();
        Document document = DocumentHelper.parseText(content);
        List<Node> contents = document.getRootElement().content();
        contents.forEach(a->{
            if (a.getNodeType() == Node.ELEMENT_NODE){
                Element temp = (Element)a;
                if (temp.getName().equals("p")){
                    if(temp.element("br")!=null){
                        String style = ItemType.NEXT_LINE;
                        Paragraph p = Paragraph.builder().rows(new ArrayList<Row>()).type(style).lvl(0).build();
                        paragraphs.add(p);
                    }else{
                        String style = getItemType(contContent.getPageType(),contContent.getItemType(),contContent.getAlias(),false);
                        Paragraph p = Paragraph.builder().rows(nodeExecute(temp,style)).type(style).lvl(lvl).build();
                        paragraphs.add(p);
                    }

                }else if(temp.getName().equals("ol")){
                    String style = getItemType(contContent.getPageType(),contContent.getItemType(),contContent.getAlias(),true);
                    List<Element> li = temp.elements("li");
                    li.forEach(element -> {
                        Element pElement = element.element("p");
                        Paragraph p = Paragraph.builder().rows(nodeExecute(pElement,style)).type(style).lvl(lvl).build();
                        paragraphs.add(p);
                    });
                }
            }else if (a.getNodeType() == Node.TEXT_NODE){
                String style = getItemType(contContent.getPageType(),contContent.getItemType(),contContent.getAlias(),false);
                Paragraph p = Paragraph.builder().rows(Lists.newArrayList(Row.builder().content(a.getText()).style(getItemType(contContent.getPageType(),contContent.getItemType(),contContent.getAlias(),false)).build())).type(style).lvl(lvl).build();
                paragraphs.add(p);
            }
        });
        List<Paragraph> result = Lists.newArrayList();
        List<String> collect = contVariableDao.selectByExample(new ContVariableExample()).stream().filter(a -> "table".equals(a.getVarType())).map(ContVariable::getVarName).collect(Collectors.toList());

        for (int i = 0; i < paragraphs.size(); i++) {
            dealValue(result,getContValue(contMain,contVariables),collect,paragraphs.get(i));
          }

        return result;
    }
    public void dealValue(List<Paragraph> paragraphs,Map<String,String> values,List<String> tableValues,Paragraph p){
            int start = 0;
            List<Row> rows = p.getRows();
            List<Paragraph> tempList = Lists.newArrayList();
            for (int j = 0; j < rows.size(); j++) {
                Row row = rows.get(j);
                List<String> variable = StringUtil.getVariable(row.getContent());
                for (int k = 0; k < variable.size(); k++) {
                    if (values.keySet().contains(variable.get(k))){
                        System.out.println("---------------------"+row.toString());
                        row.setContent(row.getContent().replace("${"+variable.get(k)+"}",values.get(variable.get(k))==null?"":values.get(variable.get(k))));
                    }
                }
                List<String> tableVariables = StringUtil.getVariable(row.getContent());
                if(tableVariables.size()>0){
                    String[] split = row.getContent().split("\\$\\{([0-9a-zA-Z\\u4e00-\\u9fa5]*)\\}");
                    List<Row> tempRows =Lists.newArrayList( rows.subList(start,j));

                    for (int l = 0; l < split.length; l++) {
                        tempRows.add(Row.builder().styles(rows.get(j).getStyles()).style(rows.get(j).getStyle()).content(split[l]).build());
                    }
                    tempList.add(Paragraph.builder().xml(p.getXml()).lvl(p.getLvl()).rows(tempRows).orderCode(p.getOrderCode()).type(p.getType()).build());

                    tableVariables.forEach(a->{
                        tempList.add(Paragraph.builder().type(ItemType.TABLE).orderCode(0).xml(a).lvl(0).rows(new ArrayList<>()).build());
                    });
                }

            }
            if (tempList.size() == 0 ){
                paragraphs.add(p);
            }else{
                paragraphs.addAll(tempList);
            }


    }
    public List<Row> nodeExecute(Element node,String style){
        List<Row> rows = Lists.newArrayList();
        List<Node> nodes = Lists.newArrayList();
        allElement(nodes,node);
        nodes.forEach(a->{
            String text = a.getText();
            List<String> styles = Lists.newArrayList();
            while (a.getParent()!=null){
                Element temp = a.getParent();
                if ("span".equals(temp.getName())&&temp.attributeValue("style")!=null&&temp.attributeValue("style").indexOf("underline")>0 ){
                    styles.add("u");
                }else if ("em".equals(temp.getName())){
                    styles.add("i");
                }else if ("strong".equals(temp.getName())){
                    styles.add("b");
                }
                a = temp;
            }
            if (!"".equals(text)){
                Row row = Row.builder().style(style).content(text).styles(styles).build();
                rows.add(row);
            }
        });
        return rows;
    }

    public void allElement(List<Node> nodes , Node node){
        if (node.getNodeType() == Node.ELEMENT_NODE){
            Element temp = (Element)node;
            if (temp.elements().size() == 0 ){
                nodes.add(temp);
            }else{
                List<Node> elements = temp.content();
                for (int i = 0; i < elements.size(); i++) {
                    allElement(nodes,elements.get(i));
                }
            }
        }else{
            nodes.add(node);
        }
    }
    @Override
    public void contContentSort(List<ContContent> start,List<ContContent> original,AtomicInteger count){
        for (int i = 0; i < start.size(); i++) {
            ContContent contContent = start.get(i);
            for (int j = 0; j < original.size(); j++) {
                if (original.get(j).getObjuid().equals(start.get(i).getObjuid())){
                    original.get(j).setOrder(count.addAndGet(1));
                }
            }
            List<ContContent> collect = original.stream().filter(a -> contContent.getObjuid().equals(a.getParentUid())).sorted(Comparator.comparingInt(ContContent::getOrderCode)).collect(Collectors.toList());
            if (collect.size()>0){
                contContentSort(collect,original,count);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("${2}${3}".split("\\$\\{([0-9a-zA-Z\\u4e00-\\u9fa5]*)\\}")[0]);
    }


}
